package breadbox.client.logging;

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;


/**
 * A FileInput implementation for reading LogChunks from log files
 * @author Forrest
 *
 */

public class LogFileInput {
	
	protected File f;
	protected FileInputStream fileIn;
	
	/**
	 * Construct a new FileInput
	 * @param filename String
	 * @param compression boolean
	 */
	public LogFileInput(String filename) {
		f = new File(Log.LOG_DIRECTORY + "/" + filename + Log.LOG_FILE_EXTENSION);
		try {
			fileIn = new FileInputStream(f);
		} catch (FileNotFoundException e) {}
	}
	
	/**
	 * Close the input streams
	 * @throws IOException
	 */
	protected void close() throws IOException {
		fileIn.close();
	}
	
	/**
	 * Read a single chunk from the log
	 * @return Chunk next LogChunk from file
	 * @throws IOException 
	 * @throws IOException 
	 * @throws NullPointerException when no Chunks found
	 */
	public List<LogChunk> readAllChunks() throws IOException {
		ObjectInputStream object_in = new ObjectInputStream(this.fileIn);
		List<LogChunk> chunks = new ArrayList<LogChunk>();
		while (true) {
			try {
				LogChunk k = (LogChunk)object_in.readObject();
				chunks.add(k);
			} catch (ClassNotFoundException e) {
				System.err.println("Log error: Cannot load log file");
			} catch (EOFException e) {
				break;
			} catch (IOException e) {
				System.err.println("Log error: Cannot read log file");
			}
		}
		object_in.close();
		this.close();
		return chunks;
	}
}
